﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace YDT.Projects.WebSite.CacheHttpClient
{
    /// <summary>
    /// 自定义
    /// </summary>
    public class CacheHttpClientMessageHanlder : DelegatingHandler
    {
        private readonly IMemoryCache _memoryCache;// 本地缓存
        private readonly IDistributedCache _distributedCache; // 分布式缓存

        public CacheHttpClientMessageHanlder(IMemoryCache memoryCache, 
            IDistributedCache distributedCache)
        {
            _memoryCache = memoryCache;
            _distributedCache = distributedCache;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // 2、本地缓存
            HttpResponseMessage httpResponseMessage = _memoryCache.Get<HttpResponseMessage>(request.RequestUri.AbsoluteUri);

            // 3、获取响应头中，
            if (httpResponseMessage == null)
            {
                // 2.1、从远程查找
                httpResponseMessage = base.SendAsync(request, cancellationToken).Result;

                // 2.2、是否需要缓存
                CacheControlHeaderValue cacheControl = httpResponseMessage.Headers.CacheControl;
                var NoCache = cacheControl.NoCache;
                var NoStore = cacheControl.NoStore;
                var MaxAge = cacheControl.MaxAge;
                if (!NoCache && !NoStore)
                {
                    // 1、设置缓存过期时间
                    MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions();
                    memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = MaxAge; // 过期时间

                    // 2.2、存储到本地缓存中
                    _memoryCache.Set<HttpResponseMessage>(request.RequestUri.AbsoluteUri, httpResponseMessage, memoryCacheEntryOptions);
                }
                return Task.FromResult(httpResponseMessage);
            } else
            {
                // 2.2、是否直接返回缓存数据
                CacheControlHeaderValue cacheControl = httpResponseMessage.Headers.CacheControl;
                var NoCache = cacheControl.NoCache; // 1、是否缓存
                var NoStore = cacheControl.NoStore; // 2、是否存储
                var MaxAge = cacheControl.MaxAge;
                if (!NoCache || !NoStore)
                {
                    return Task.FromResult(httpResponseMessage);
                } else
                {
                    httpResponseMessage = base.SendAsync(request, cancellationToken).Result;

                    return Task.FromResult(httpResponseMessage);
                }
            }
        }
    }
}
